//
//  ClassB.m
//  LittleSummary
//
//  Created by 郝旭珊 on 2018/3/20.
//  Copyright © 2018年 郝旭珊. All rights reserved.
//

#import "ClassB.h"
#import <objc/runtime.h>


@interface ClassB()

@end

@implementation ClassB

//- (void)run{
//
//}


//注释掉 run ，但是运行后发现 newRun 方法，编译也没有报错
//这就是动态绑定
//
+ (BOOL)resolveInstanceMethod:(SEL)sel{
    NSLog(@"sel%@",NSStringFromSelector(sel));

    if (sel == @selector(run)){
        //强写，无提示
        class_addMethod(self,sel,(IMP)newRun,"v@:");
        return YES;
    }
    return [super resolveInstanceMethod:sel];
}

void newRun(id self, SEL sel){
    NSLog(@"is running");
}

//消息重定向
- (id)forwardingTargetForSelector:(SEL)aSelector{
    NSLog(@"sel%@",NSStringFromSelector(aSelector));
    return [super forwardingTargetForSelector:aSelector];
}

//方法签名
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector{
    NSString *selString = NSStringFromSelector(aSelector);
    if([selString isEqualToString:@"run"]){
        return [NSMethodSignature signatureWithObjCTypes:"v@:"];
    }else{
        return [super methodSignatureForSelector:aSelector];
    }
}

/*
 v@: 去苹果官网 Guides
 */

//拿到方法签名后进行消息配发
- (void)forwardInvocation:(NSInvocation *)anInvocation{
    NSLog(@"%@",anInvocation);
    SEL selector = [anInvocation selector];

    //转发
    ClassA *a = [ClassA new];
    if ([a respondsToSelector:selector]){
        [anInvocation invokeWithTarget:a];

    }else{
        return [super forwardInvocation:anInvocation];
    }
    

    
}

@end
